package cloud.shyidong.core.controller;

import cloud.shyidong.core.Result;
import cloud.shyidong.core.exception.BusinessException;
import cloud.shyidong.core.util.CosUtil;
import cloud.shyidong.core.util.SpringUtils;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.UploadResult;
import com.qcloud.cos.transfer.Upload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Description TODO
 * @Author syd
 * @Date 2023/10/13
 */
@Slf4j
public class UploadController {
    
    /**
     * 上传文件到cos存储桶
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        
        if (file.isEmpty()) {
            throw BusinessException.from("上传失败");
        }
        
        //上传文件名
        String fileName = file.getOriginalFilename();
        log.info("old fileName:{}", fileName);
        
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = System.currentTimeMillis() + fileType;
        
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(file.getInputStream().available());
            PutObjectRequest putObjectRequest = new PutObjectRequest(SpringUtils.getProperty("cos.bucket.name"), newFileName, file.getInputStream(), new ObjectMetadata());
            Upload upload = CosUtil.getTransferManager().upload(putObjectRequest);
            UploadResult uploadResult = upload.waitForUploadResult();
            return Result.ofData(uploadResult);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw BusinessException.from("上传失败");
        }
        
    }
    
}
